package com.ruoyi.web.controller.exa;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.exa.domain.ExaParper;
import com.ruoyi.exa.service.IExaParperService;
import com.ruoyi.web.controller.api.vo.ExaBitchResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.exa.domain.ExaBitchUser;
import com.ruoyi.exa.service.IExaBitchUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 批次员工Controller
 * 
 * @author linziheng
 * @date 2025-06-13
 */
@Api("员工批次Controller")
@RestController
@RequestMapping("/exa/user")
public class ExaBitchUserController extends BaseController
{
    @Autowired
    private IExaBitchUserService exaBitchUserService;
    @Autowired
    private IExaParperService iExaParperService;
    @Autowired
    private IExaBitchUserService iExaBitchUserService;

    /**
     * 查询批次员工列表
     */
    @ApiOperation("查询批次员工列表")
    @PreAuthorize("@ss.hasPermi('exa:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExaBitchUser exaBitchUser)
    {
        startPage();
        //获取当前登录用户
        SysUser user = getLoginUser().getUser();
        exaBitchUser.setUserId(user.getUserId());
        List<ExaBitchUser> list = exaBitchUserService.selectExaBitchUserAllList(exaBitchUser);
        return getDataTable(list);
    }

    /**
     * 查询批次员工列表
     */
    @ApiOperation("查询考试结果列表")
    @PreAuthorize("@ss.hasPermi('exa:user:resultList')")
    @GetMapping("/resultList")
    public TableDataInfo resultList(ExaBitchUser exaBitchUser)
    {
        startPage();
        List<ExaBitchUser> list = exaBitchUserService.selectExaBitchUserList(exaBitchUser);
        //获取所有试卷
        List<ExaParper> exaParperList = iExaParperService.selectExaParperList(new ExaParper());
        for (ExaBitchUser bitchUser:list){
            List<ExaParper> collectParPer = exaParperList.stream().filter(p -> p.getId() == bitchUser.getParperId()).collect(Collectors.toList());
            //总答题时间
            Long surplusTime = bitchUser.getRemainingTime()!=null?bitchUser.getRemainingTime():0;
            Long answerTime = collectParPer.get(0).getAnsweringTime()-surplusTime;
            bitchUser.setAnswerTime(answerTime);
            bitchUser.setParperScore(collectParPer.get(0).getParperScore());
        }
        return getDataTable(list);
    }

    @ApiOperation("查询通过率")
    @GetMapping("/selectRate")
    public AjaxResult selectRate(Long bitchId){
        ExaBitchResultVo exaBitchResultVo = new ExaBitchResultVo();
        ExaBitchUser exaBitchUser = new ExaBitchUser();
        exaBitchUser.setBitchId(bitchId);
        //该批次所有参加考试人员
        List<ExaBitchUser> exaBitchUserList = iExaBitchUserService.selectExaBitchUserList(exaBitchUser);
        exaBitchResultVo.setParperNum(exaBitchUserList.size());

        //参考人数
        List<ExaBitchUser> collectTaskExam = exaBitchUserList.stream().filter(e -> !e.getStatus().equals("0")).collect(Collectors.toList());
        exaBitchResultVo.setTaskExamNum(collectTaskExam.size());

        //已通过人数
        List<ExaBitchUser> collectPass = exaBitchUserList.stream().filter(e -> e.getIsPass().equals("1")).collect(Collectors.toList());
        exaBitchResultVo.setPassNum(collectPass.size());

        //未通过人数
        List<ExaBitchUser> collectUnPass = exaBitchUserList.stream().filter(e -> e.getIsPass().equals("0")).collect(Collectors.toList());
        exaBitchResultVo.setUnPassNum(collectUnPass.size());

        //未完成人数
        List<ExaBitchUser> collectIncomplete = exaBitchUserList.stream().filter(e -> e.getStatus().equals("4")).collect(Collectors.toList());
        exaBitchResultVo.setIncompleteNum(collectIncomplete.size());
        if(exaBitchUserList.size()>0){
            //通过率
            exaBitchResultVo.setPassRate(new BigDecimal(collectPass.size()).divide(new BigDecimal(exaBitchUserList.size()),2, RoundingMode.HALF_UP));
        }else {
            exaBitchResultVo.setPassRate(new BigDecimal(0));
        }
        return success(exaBitchResultVo);
    }

    /**
     * 导出批次员工列表
     */
    @PreAuthorize("@ss.hasPermi('exa:user:export')")
    @Log(title = "批次员工", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExaBitchUser exaBitchUser)
    {
        List<ExaBitchUser> list = exaBitchUserService.selectExaBitchUserList(exaBitchUser);
        //获取所有试卷
        List<ExaParper> exaParperList = iExaParperService.selectExaParperList(new ExaParper());
        for (ExaBitchUser bitchUser:list){
            List<ExaParper> collectParPer = exaParperList.stream().filter(p -> p.getId() == bitchUser.getParperId()).collect(Collectors.toList());
            //总答题时间
            Long surplusTime = bitchUser.getRemainingTime()!=null?bitchUser.getRemainingTime():0;
            Long answerTime = collectParPer.get(0).getAnsweringTime()-surplusTime;
            bitchUser.setAnswerTime(answerTime);
            bitchUser.setParperScore(collectParPer.get(0).getParperScore());
        }
        ExcelUtil<ExaBitchUser> util = new ExcelUtil<ExaBitchUser>(ExaBitchUser.class);
        util.exportExcel(response, list, "批次员工数据");
    }

    /**
     * 获取批次员工详细信息
     */
    @PreAuthorize("@ss.hasPermi('exa:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(exaBitchUserService.selectExaBitchUserById(id));
    }

    /**
     * 新增批次员工
     */
    @PreAuthorize("@ss.hasPermi('exa:user:add')")
    @Log(title = "批次员工", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExaBitchUser exaBitchUser)
    {
        return toAjax(exaBitchUserService.insertExaBitchUser(exaBitchUser));
    }

    /**
     * 修改批次员工
     */
    @PreAuthorize("@ss.hasPermi('exa:user:edit')")
    @Log(title = "批次员工", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改员工批次")
    public AjaxResult edit(@RequestBody ExaBitchUser exaBitchUser)
    {
        return toAjax(exaBitchUserService.updateExaBitchUser(exaBitchUser));
    }

    @GetMapping("/editScore")
    @ApiOperation("判卷")
    public AjaxResult editScore(Long id,Long parperId,Long score){
        ExaBitchUser exaBitchUser = exaBitchUserService.selectExaBitchUserById(id);
        ExaParper exaParper = iExaParperService.selectExaParperById(parperId);
        if(score >= exaParper.getPassScore()){
            exaBitchUser.setIsPass("1");
        }else {
            exaBitchUser.setIsPass("0");
        }
        exaBitchUser.setScore(score);
        exaBitchUser.setStatus("3");
        return toAjax(exaBitchUserService.updateExaBitchUser(exaBitchUser));
    }

    /**
     * 点击开始答题修改状态
     * @param id 员工批次ID
     * @return 修改
     */
    @GetMapping("/editStatus")
    @ApiOperation("开始答题修改状态")
    public AjaxResult editStatus(Long id){
        ExaBitchUser exaBitchUser = exaBitchUserService.selectExaBitchUserById(id);
        exaBitchUser.setStatus("1");
        exaBitchUser.setStartTime(DateUtils.getNowDate());
        return toAjax(exaBitchUserService.updateExaBitchUser(exaBitchUser));
    }

    /**
     * 删除批次员工
     */
    @PreAuthorize("@ss.hasPermi('exa:user:remove')")
    @Log(title = "批次员工", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(exaBitchUserService.deleteExaBitchUserByIds(ids));
    }
}
